// 导出报表（单表）
import {
  ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE,
  ENTERPRISE_BASIC_INFORMATION_TABLE_ID,
  PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE,
  ENERGY_CONSUMPTION_STRUCTURE_TABLE,
  ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE,
  TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT,
} from '@/config'
import { withStyle } from '@/utils/sheet'
import { utils, writeFile } from 'xlsx-js-style'
/* IFTRUE_ONLY_NANCHANG
import {
  exportUnitDetails,
  exportEnergyConsumptionStructure,
  exportEnergyConsumptionStructureSchedule,
  exportProductEnergyConsumption,
  exportGoalCompletionStatus,
  exportReconstructionProject,
  exportReport,
} from '@/api/enterpriseQuarterlyReport2'
FITRUE_ONLY_NANCHANG */
/* IFTRUE_NOT_NANCHANG */
import {
  exportUnitDetails,
  exportEnergyConsumptionStructure,
  exportEnergyConsumptionStructureSchedule,
  exportProductEnergyConsumption,
  exportGoalCompletionStatus,
  exportReconstructionProject,
  exportReport,
} from '@/api/enterpriseQuarterlyReport'
/* FITRUE_NOT_NANCHANG */
function export_excel_report_report_1 () {
  const quarterlyAccountTable = this.$refs.quarterlyAccountTable
  if (!quarterlyAccountTable) return;

  const flattenColumns = quarterlyAccountTable.flattenColumns
  const lists = quarterlyAccountTable.getData() || [];
  const summary = quarterlyAccountTable.summary
  const informer = quarterlyAccountTable.getInformer()
  const desc = quarterlyAccountTable.tableDescription || ''
  const consumptionThisYear = quarterlyAccountTable.currentValue
  const consumptionLastYear = quarterlyAccountTable.previousValue
  const seriesNo = quarterlyAccountTable.seriesNo || ''
  const title = (quarterlyAccountTable.title || '') + (seriesNo ? `（${seriesNo}） ` : '')

  const is_enterprise_basic_information_table = (+this.tableAccountId) === ENTERPRISE_BASIC_INFORMATION_TABLE_ID;
  const is_energy_saving_renovation_project_information_table = (+this.tableAccountId) === ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE.ID;

  const appendInformant = v => ([
    fill({}),
    fill([]),
    ['填报负责人：', v.personInCharge, '填报人：', v.informer, '电话：', v.telephone, '填报日期：', v.fillInDate],
  ])
  const appendDescription = (v) => {
    const getDesc = (value) => {
      if (value) {
        return value.replace(/\n\t/g, '\n').split(/\n/)
      }
      return []
    }
    v = getDesc(v);
    return [
      [],
      ...v.map(v => [v])
    ]
  }

  const fill = (v) => flattenColumns.map(col => {
    const prop = col.prop
    const vv = v[prop]
    return v[prop] === '' ? '' : vv;
  })

  let aoa = []

  if (is_enterprise_basic_information_table) {
    const v = { ...lists.data, list: lists.list }
    const keys = [
      'productName',
      'quantity',
      'unitOfMeasurement',
      'quantityOne',
      'unitOfMeasurementOne',
      'numericalValue',
      'unitOfMeasurementTwo',
    ]
    const header_9 = [
      // ['单位名称', v.tenantName, '', '', '年度', '', v.year, ''],
      ['所属地区', v.ssdq, '所属领域', v.ssly, '行业', v.hy, '单位类型', v.dwlx],
      ['单位详细名称', v.dwxxmc, '', '', '社会信用代码', v.shxydm, '', ''],
      ['单位注册日期', v.dwzcrq, '', '', '单位注册资本（万元）', v.dwzczb, '', ''],
      ['法定代表人姓名', v.fddbrxm, '', '', '联系电话（区号）', v.lxdh, '', ''],
      ['是否央企', v.sfyq, '', '', '所属央企集团名称', v.ssyqjtmc, '', ''],
      ['单位地址', v.dwdz, '', '', '邮政编码', v.yzbm, '', ''],
      ['行政区划代码', v.xzqhdm, '', '', '电子邮箱', v.dzyx, '', ''],
      ['能源管理机构名称', v.nygljgmc, '', '', '传真（区号）', v.cz, '', ''],
      ['主管节能领导姓名', v.zgjnldxm, '', '', '联系电话（区号）', v.lxdh1, '', ''],
      ['能源管理负责人姓名', v.nyglfzrxm, '手机', v.sj, '能源管理师证号', v.nyglszh, '', ''],
      ['是否通过能源管理体系认证', v.sftgnygltxrz, '通过日期', v.tgrq, '认证机构', v.rzjg, '', ''],
      ['指标名称', '', '计量单位', '本期值', '上年值', '同比变化率（%）', '产值及能源消费变化 情况说明 ', ''],
      // ['工业总产值', '', '万元', v.bqgyzcz, v.sngyzcz, v.tbgyzcz, v.bz, ''],
      // ['价格指数', '', '%', v.bqjgzs, v.snjgzs, v.tbjgzs, '', ''],
      ['工业总产值(可比价)', '', '万元', v.bqgyzczkbj, v.sngyzczkbj, v.tbgyzczkbj, v.bz, ''],
      ['销售收入', '', '万元', v.bqxssr, v.snxssr, v.tbxssr, '', ''],
      ['上缴利税', '', '万元', v.bqsjls, v.snsjls, v.tbsjls, '', ''],
      ['从业人员', '', '人', v.bqcyry, v.sncyry, v.tbcyry, '', ''],
      ['能源管理师人数', '', '人', v.bqnyglsrs, v.snnyglsrs, v.tbnyglsrs, '', ''],
      ['综合能源消费量(当量值)', '', '万吨标准煤', v.bqzhnyxfl, v.snzhnyxfl, v.tbzhnyxfl, '', ''],
      ['生产成本', '', '万元', v.bqsccb, v.snsccb, v.tbsccb, '', ''],
      ['能源消费成本', '', '万元', v.bqnyxfcb, v.snnyxfcb, v.tbnyxfcb, '', ''],
      ['能源消费占生产成本比例', '', '%', v.bqnyxfzsccbbl, v.snnyxfzsccbbl, v.tbnyxfzsccbbl, '', ''],
      ['单位总产值综合能耗(当量值)', '', '吨标准煤/万元', v.bqdwzczzhnh, v.sndwzczzhnh, v.tbdwzczzhnh, '', ''],
      ['主要产品名称', '', '年产能', '', '年产量', '', '单位产品能耗', ''],
      ['', '', '数量', '计量单位', '数量', '计量单位', '数值', '计量单位'],
      ...(v.list || []).map(vv => {
        const item = keys.map(key => vv[key])
        item.splice(1, 0, '')
        return item
      })
    ]
    aoa.push(...header_9)
  } else {
    aoa = [
      ...aoa,
      (flattenColumns || []).map(v => v.label + (v.unit ? `（${v.unit}）` : '')),
    ]
    lists.forEach((v, i) => {
      const data = fill(v)
      if (is_energy_saving_renovation_project_information_table) {
        data[0] = i + 1
      }
      // console.log(data);
      aoa.push(data)
    })
  }

  if (+this.tableAccountId === PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE.ID) {
    let r = ''
    if (quarterlyAccountTable.get_progress_description) {
      r = quarterlyAccountTable.get_progress_description()
    }
    aoa.push(
      ['进度节能量目标完成情况说明', '', '', r, '', '', '', '']
    )
  }

  // 合计
  if (summary) {
    const d = summary.data.reduce((acc, v) => {
      acc[v.key] = String(v.value || '')
      return acc
    }, {})
    const data = fill(d)
    aoa.push(data)
  }

  aoa = withStyle(aoa);

  // 本年综合能源消费量（当量值）
  // 上年综合能源消费量（当量值）
  // consumptionLastYear consumptionThisYear
  if (consumptionLastYear != null && consumptionThisYear != null) {
    aoa.push([])
    aoa.push(
      ['本年综合能源消费量（当量值）', consumptionThisYear || '', ' 万吨标准煤', '上年综合能源消费量（当量值）', consumptionLastYear || '', ' 万吨标准煤']
    )
  }

  aoa.push(
    ...appendInformant(informer),
    ...appendDescription(desc)
  )


  aoa.unshift([{
    v: title,
    s: {
      font: {
        sz: 14,
        bold: true,
      },
      alignment: {
        vertical: 'center',
        horizontal: 'center',
      },
    }
  }])

  const fileName = title + '.xlsx';
  const wb = utils.book_new();
  const ws = utils.aoa_to_sheet(aoa)

  if (is_enterprise_basic_information_table) {
    ws['!merges'] = [
      { s: { r: 0, c: 0 }, e: { r: 0, c: 7 } },
      { s: { r: 1, c: 1 }, e: { r: 1, c: 3 } }, { s: { r: 1, c: 5 }, e: { r: 1, c: 7 } },
      { s: { r: 2, c: 1 }, e: { r: 2, c: 3 } }, { s: { r: 2, c: 5 }, e: { r: 2, c: 7 } },
      { s: { r: 3, c: 1 }, e: { r: 3, c: 3 } }, { s: { r: 3, c: 5 }, e: { r: 3, c: 7 } },
      { s: { r: 4, c: 1 }, e: { r: 4, c: 3 } }, { s: { r: 4, c: 5 }, e: { r: 4, c: 7 } },
      { s: { r: 5, c: 1 }, e: { r: 5, c: 3 } }, { s: { r: 5, c: 5 }, e: { r: 5, c: 7 } },
      { s: { r: 6, c: 1 }, e: { r: 6, c: 3 } }, { s: { r: 6, c: 5 }, e: { r: 6, c: 7 } },
      { s: { r: 7, c: 1 }, e: { r: 7, c: 3 } }, { s: { r: 7, c: 5 }, e: { r: 7, c: 7 } },
      { s: { r: 8, c: 1 }, e: { r: 8, c: 3 } }, { s: { r: 8, c: 5 }, e: { r: 8, c: 7 } },
      { s: { r: 9, c: 1 }, e: { r: 9, c: 3 } }, { s: { r: 9, c: 5 }, e: { r: 9, c: 7 } },

      { s: { r: 10, c: 4 }, e: { r: 10, c: 5 } }, { s: { r: 10, c: 6 }, e: { r: 10, c: 7 } },
      { s: { r: 11, c: 4 }, e: { r: 11, c: 5 } }, { s: { r: 11, c: 6 }, e: { r: 11, c: 7 } },
      { s: { r: 12, c: 0 }, e: { r: 12, c: 1 } }, { s: { r: 12, c: 4 }, e: { r: 12, c: 5 } }, { s: { r: 12, c: 6 }, e: { r: 12, c: 7 } },
      { s: { r: 13, c: 0 }, e: { r: 13, c: 1 } }, { s: { r: 13, c: 4 }, e: { r: 13, c: 5 } }, { s: { r: 13, c: 6 }, e: { r: 24, c: 7 } },
      { s: { r: 14, c: 0 }, e: { r: 14, c: 1 } }, { s: { r: 14, c: 4 }, e: { r: 14, c: 5 } },
      { s: { r: 15, c: 0 }, e: { r: 15, c: 1 } }, { s: { r: 15, c: 4 }, e: { r: 15, c: 5 } },
      { s: { r: 16, c: 0 }, e: { r: 16, c: 1 } }, { s: { r: 16, c: 4 }, e: { r: 16, c: 5 } },
      { s: { r: 17, c: 0 }, e: { r: 17, c: 1 } }, { s: { r: 17, c: 4 }, e: { r: 17, c: 5 } },
      { s: { r: 18, c: 0 }, e: { r: 18, c: 1 } }, { s: { r: 18, c: 4 }, e: { r: 18, c: 5 } },
      { s: { r: 19, c: 0 }, e: { r: 19, c: 1 } }, { s: { r: 19, c: 4 }, e: { r: 19, c: 5 } },
      { s: { r: 20, c: 0 }, e: { r: 20, c: 1 } }, { s: { r: 20, c: 4 }, e: { r: 20, c: 5 } },
      { s: { r: 21, c: 0 }, e: { r: 21, c: 1 } }, { s: { r: 21, c: 4 }, e: { r: 21, c: 5 } },
      { s: { r: 22, c: 0 }, e: { r: 22, c: 1 } }, { s: { r: 22, c: 4 }, e: { r: 22, c: 5 } },
      { s: { r: 23, c: 0 }, e: { r: 23, c: 1 } }, { s: { r: 23, c: 4 }, e: { r: 23, c: 5 } },
      { s: { r: 24, c: 0 }, e: { r: 24, c: 1 } }, { s: { r: 24, c: 4 }, e: { r: 24, c: 5 } },
      { s: { r: 25, c: 0 }, e: { r: 26, c: 1 } }, { s: { r: 25, c: 2 }, e: { r: 25, c: 3 } }, { s: { r: 25, c: 4 }, e: { r: 25, c: 5 } }, { s: { r: 25, c: 6 }, e: { r: 25, c: 7 } },
      { s: { r: 26, c: 7 }, e: { r: 26, c: 7 } },
      { s: { c: 0 }, e: { c: 1 } }, { s: { c: 7 }, e: { c: 7 } },
    ]
  } else {
   ws['!merges'] = [
    { s: { r: 0, c: 0 }, e: { r: 0, c: flattenColumns.length - 1 } },
   ]
  }

  utils.book_append_sheet(wb, ws, 'sheet1');
  writeFile(wb, fileName)
}

function export_excel (tableId, enterprise = '', fiveYearsColumns = {}) {
  const quarterlyAccountTable = this.$refs.quarterlyAccountTable

  if (!quarterlyAccountTable) {
    console.warn('this.$refs.quarterlyAccountTable is ', quarterlyAccountTable)
    return
  }

  const tId = +tableId
  const informer = quarterlyAccountTable.getInformer() || {}
  const consumptionThisYear = quarterlyAccountTable.currentValue || ''
  const consumptionLastYear = quarterlyAccountTable.previousValue || ''
  const lists = quarterlyAccountTable.getData() || [];
  const summary = quarterlyAccountTable.summary
  const get_progress_description = quarterlyAccountTable.get_progress_description

  const yuan_mei_qi_zhong_xiang = (lists) => lists.map(v => {
    if (v.code === '02') return { ...v, energyName: ' 其中：1.无烟煤' }
    if (v.code === '03') return { ...v, energyName: '           2.炼焦烟煤' }
    if (v.code === '04') return { ...v, energyName: '           3.一般烟煤' }
    if (v.code === '05') return { ...v, energyName: '           4.褐煤' }
    return {
      ...v,
    }
  })

  const time = (+this.quarter) === 5
    ? `${this.year}年`
    : `${this.year}年第${this.quarter}季度`;

  let method = null
  let data = {
    time,
    enterprise,
    personInCharge: informer.personInCharge || '',
    telephone: informer.telephone || '',
    informer: informer.informer || '',
    date: informer.fillInDate || '',
  }

  /* eslint-disable brace-style */
  // 表1-1
  if (tId === ENTERPRISE_BASIC_INFORMATION_TABLE_ID) {
    method = exportUnitDetails
    data = {
      ...data,
      ...(lists.data || {}),
      product: lists.list || [],
    }
  }
  // 表1-2
  else if (tId === ENERGY_CONSUMPTION_STRUCTURE_TABLE.ID) {
    method = exportEnergyConsumptionStructure
    data = {
      ...data,
      structure: yuan_mei_qi_zhong_xiang(lists || [])
    }
    if (summary) {
      const d = summary.data.reduce((acc, v) => {
        acc[v.key] = String(v.value || '')
        return acc
      }, {})
      data.structure.push(d)
    } else {
      console.warn('表1-2 summary is ', summary)
    }
  }
  // 表1-2-1
  else if (tId === ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE.ID) {
    method = exportEnergyConsumptionStructureSchedule
    data = {
      ...data,
      consumptionThisYear,
      consumptionLastYear,
      schedule: yuan_mei_qi_zhong_xiang(lists || [])
    }
    if (summary) {
      const d = summary.data.reduce((acc, v) => {
        acc[v.key] = String(v.value || '')
        return acc
      }, {})
      data.schedule.push(d)
    } else {
      console.warn('表1-2-1 summary is ', summary)
    }
  }
  // 表1-3
  else if (tId === TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT.ID) {
    method = exportProductEnergyConsumption
    data = {
      ...data,
      product: lists || []
    }
  }
  // 表1-4
  else if (tId === PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE.ID) {
    method = exportGoalCompletionStatus
    data = {
      ...data,
      reportDescription: get_progress_description ? get_progress_description() : '',
      goal: lists || [],

      // 五年计划
      column1: fiveYearsColumns.column1 || '',
      column2: fiveYearsColumns.column2 || '',
      column3: fiveYearsColumns.column3 || '',
      column4: fiveYearsColumns.column4 || '',
      column5: fiveYearsColumns.column5 || '',
    }
  }
  // 表1-5
  else if (tId === ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE.ID) {
    method = exportReconstructionProject
    data = {
      ...data,
      project: (lists || []).map((v, i) => ({
        ...v,
        // 序号
        serialNumber: i + 1,
      })),
    }
  }
  /* eslint-enable brace-style */

  if (method) {
    // console.log(data)
    method(data).then(res => {
      downloadRes(res)
    }).catch(e => {
      console.warn(e)
    })
  }
}

function downloadRes (res) {
  const { data, headers } = res
  const fileName = (headers['content-disposition'] || '')
    .replace(/\s/g, '')
    .replace(/\w+;filename=(.*)/, '$1')
  const blob = new Blob([data], { type: headers['content-type'] })
  const dom = document.createElement('a')
  const url = window.URL.createObjectURL(blob)
  dom.href = url
  dom.download = decodeURI(fileName)
  dom.style.display = 'none'
  document.body.appendChild(dom)
  dom.click()
  dom.parentNode.removeChild(dom)
  window.URL.revokeObjectURL(url)
}

export default {
  methods: {
    export_excel_report_report () {
      return export_excel.call(
        this,
        this.tableAccountId,
        this.selectEnterpriseId ? this.selectEnterpriseName : this.enterpriseName,
        this.fiveYearsColumns,
      )
    },
    export_excel_report_report_1,
    export_excel_multiple_sheets (year, quarter, enterpriseId) {
      return exportReport(year, quarter, enterpriseId).then(res => {
        downloadRes(res)
      })
    }
  }
}
